<template>
  <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>卡座信息</span>
      <el-button style="float: right; margin-left: 10px;" type="primary" size="mini" @click="showAddDialog()">新增卡座</el-button>
    </el-card>
    
    <div class="card-container">
      <el-row :gutter="20">
        <el-col v-for="seat in seatList" :key="seat.id" :span="6" 
          class="seat-card-col">
          <el-card class="seat-card" :class="{ 'active': selectedSeatId === seat.id }" @click.native="selectSeat(seat)">
            <div class="seat-actions">
              <el-button type="danger" icon="el-icon-delete" circle size="mini" @click.stop="deleteSeat(seat.id)"></el-button>
              <el-button type="primary" icon="el-icon-edit" circle size="mini" @click.stop="showAddDialog(seat)"></el-button>
            </div>
            <div class="seat-info">
              <div class="seat-id">编号: {{ seat.id }}</div>
              <div class="seat-name">名称: ({{seat.capacity }}) {{ seat.seatName }}</div>
              <div class="seat-alias">人数: {{ seat.seatingCapacity }}</div>
              <div class="seat-description">描述: {{ seat.description}}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- Time slots section - shown when a seat is selected -->
    <div v-if="selectedSeatId" class="time-slots-container">
      <el-card class="operate-container" shadow="never">
        <i class="el-icon-time"></i>
        <span>可预约时间段</span>
        <el-button style="float: right; margin-left: 10px;" type="primary" 
          size="mini" @click="showAddTimeSlotDialog">新增时段</el-button>
      </el-card>
      <el-card class="time-tags-container" shadow="never">
        <el-tag v-for="timeSlot in availableTimeSlots" :key="timeSlot.id" :type="timeSlot.type"
           size="medium" class="time-tag" :class="{ 'selected': selectedTimeSlotId === timeSlot.id }"
          @click="selectTimeSlot(timeSlot.id)">
          {{ timeSlot.startTime }} - {{ timeSlot.endTime }}
          <i class="el-icon-close delete-time-icon" @click.stop="deleteTimeSlot(timeSlot.id)"></i>
        </el-tag>
      </el-card>
    </div>

    <!-- Add Seat Dialog -->
    <el-dialog title="新增卡座" :visible.sync="addDialogVisible" width="600px">
      <el-form :model="newSeat" :rules="rules" ref="seatForm" label-width="80px">
        <el-form-item label="名称" prop="seatName">
          <el-input v-model="newSeat.seatName"></el-input>
        </el-form-item>
        <el-form-item label="属性" prop="capacity">
          <el-input v-model="newSeat.capacity"></el-input>
        </el-form-item>
        <el-form-item label="人数" prop="seatingCapacity">
          <el-input v-model="newSeat.seatingCapacity"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="newSeat.description"></el-input>
        </el-form-item>
        <el-form-item label="背景图片" prop="coverImage">
          <single-upload v-model="newSeat.coverImage"></single-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSeat()">确 定</el-button>
      </span>
    </el-dialog>
    
    <!-- Add Time Slot Dialog -->
    <el-dialog title="新增时间段" :visible.sync="addTimeSlotDialogVisible" width="400px">
      <el-form :model="newTimeSlot" :rules="timeSlotRules" ref="timeSlotForm" label-width="120px">
        <el-form-item label="时间段" prop="startTime">
          <div class="time-dialog-slots-container">
            <el-input v-model="newTimeSlot.startTime" class="time-input" placeholder="11:00" style="width: 100px;"></el-input>
            <span class="time-separator">-</span>
            <el-input v-model="newTimeSlot.endTime" class="time-input" placeholder="12:00" style="width: 100px;"></el-input>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addTimeSlotDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addTimeSlot">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { teaRoomList, seatsAddupdateInfo, timeAddupdateInfo,deleteTime,deleteSeats } from '@/api/appointment';
import SingleUpload from '@/components/Upload/singleUpload';

export default {
  components: { SingleUpload },
  data() {
    return {
      selectedSeatId: null,
      selectedTimeSlotId: null,
      addDialogVisible: false,
      addTimeSlotDialogVisible: false,
      newSeat: {
        id: 0,
        seatName: '',
        capacity: '',
        coverImage: '',
        seatingCapacity: '',
        description: ''
      },
      newTimeSlot: {
        id: 0,
        startId: 0,
        startTime: '',
        endTime: ''
      },
      seatList: [],
      timeSlots: [],
      rules: {
        seatName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        capacity: [
          { required: true, message: '请输入属性', trigger: 'blur' }
        ],
        coverImage: [
          { required: true, message: '请选择背景图片', trigger: 'blur' }
        ],
        seatingCapacity: [
          { required: true, message: '请输入人数', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入卡座描述', trigger: 'blur' }
        ]
      },
      timeSlotRules: {
        startTime: [
          { required: true, message: '请输入开始时间', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.loadTeaRoomList();
  },
  computed: {
    availableTimeSlots() {
      return this.timeSlots;
    }
  },
  methods: {
    async loadTeaRoomList() {
      try {
        const response = await teaRoomList();
        this.seatList = response.data;
        // Initialize with first seat's time slots if available
        if (this.seatList && this.seatList.length > 0) {
          this.selectSeat(this.seatList[0]);
        }
      } catch (err) {
        console.error('Failed to load tea room list:', err);
        this.$message({
          type: 'error',
          message: '加载数据失败!'
        });
      }
    },
    async loaddeleteTime(id) { 
      try { 
        const response = await deleteTime({id: id}); 
        if (response.code === 200) { 
         // Update the seatList to remove the time slot from userTeaSeatsTimes
      const selectedSeat = this.seatList.find(seat => seat.id === this.selectedSeatId);
        if (selectedSeat && selectedSeat.userTeaSeatsTimes) {
           selectedSeat.userTeaSeatsTimes = selectedSeat.userTeaSeatsTimes.filter(
           slot => slot.id !== id
         );
       }
        this.$message({
            type: 'success',
            message: '删除成功!'
          });
        } 
        return true;
      } catch (err) { 
        console.error('Failed to load seat list:', err); 
        this.$message({ 
          type: 'error', 
          message: '删除失败!' 
        }); 
        return false;
      } 
    },
    async loadDeleteSeats(seatId) { 
      try { 
        const response = await deleteSeats({id:seatId}); 
        if (response.code === 200) { 
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        } 
        return true;
      } catch (err) { 
        console.error('Failed to load seat list:', err); 
        this.$message({ 
           type: 'error', 
           message: '删除失败!' 
         }); 
        return false;
      }
    },
    async loadtimeAddupdateInfo(timeSlotData) { 
      try { 
        const response = await timeAddupdateInfo(timeSlotData);
        if (response.code === 200) {
          await this.loadTeaRoomList();
          this.$message({
            type: 'success',
            message: timeSlotData.startId > 0 ? '更新成功!' : '添加成功!'
          });
          return true;
        } else {
          throw new Error(response.message || '操作失败');
        }
      } catch (err) {
        console.error('Failed to load timeAddupdateInfo:', err);
        this.$message({
          type: 'error',
          message: '加载数据失败!'
        });
        return false;
      }
    },

    async saveSeatInfo(seatData) {
      try {
        const response = await seatsAddupdateInfo(seatData);
        if (response.code === 200) {
          await this.loadTeaRoomList();
          this.$message({
            type: 'success',
            message: seatData.id > 0 ? '更新成功!' : '添加成功!'
          });
          return true;
        } else {
          throw new Error(response.message || '操作失败');
        }
      } catch (err) {
        console.error('Save seat error:', err);
        this.$message({
          type: 'error',
          message: seatData.id > 0 ? '更新失败!' : '添加失败!'
        });
        return false;
      }
    },
    selectSeat(seat) {
      this.selectedSeatId = seat.id;
      this.timeSlots = seat.userTeaSeatsTimes || [];
      // Reset time slot selection when changing seat
      this.selectedTimeSlotId = null;
    },
    deleteSeat(seatId) {
      this.$confirm('确定要删除这个卡座吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await this.loadDeleteSeats(seatId);
          if(response){
               // Note: This should call an API to delete the seat permanently
             this.seatList = this.seatList.filter(seat => seat.id !== seatId);
             if (this.selectedSeatId === seatId) {
                this.selectedSeatId = null;
                this.timeSlots = [];
             }
          }
        } catch (err) {
          console.error('Delete seat error:', err);
          this.$message({
            type: 'error',
            message: '删除失败!'
          });
        }
      }).catch(() => {
        // User cancelled deletion
      });
    },
    showAddDialog(seat) {
      if (seat) {
        this.newSeat = { ...seat }; // Create a copy to avoid direct mutation
      } else {
        this.resetNewSeat();
      }
      this.addDialogVisible = true;
    },
    resetNewSeat() {
      this.newSeat = {
        id: 0,
        seatName: '',
        capacity: '',
        coverImage: '',
        seatingCapacity: '',
        description: ''
      };
    },
    addSeat() {
      this.$refs.seatForm.validate(async (valid) => {
        if (valid) {
          const success = await this.saveSeatInfo(this.newSeat);
          if (success) {
            this.addDialogVisible = false;
            this.resetNewSeat();
          }
        } else {
          this.$message({
            type: 'warning',
            message: '请填写必填字段!'
          });
          return false;
        }
      });
    },
    showAddTimeSlotDialog() {
      this.newTimeSlot = {
        id: 0,
        startId: this.selectedSeatId || 0,
        startTime: '',
        endTime: ''
      };
      this.addTimeSlotDialogVisible = true;
    },
    addTimeSlot() {
      this.$refs.timeSlotForm.validate(async (valid) => {
        if(valid){
          const timeSlotToSend = {...this.newTimeSlot,
            startId: this.selectedSeatId
          };
          const success = await this.loadtimeAddupdateInfo(timeSlotToSend);
          if (success) {
            this.addTimeSlotDialogVisible = false;
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
          }
        } else { 
          this.$message({
            type: 'warning',
            message: '请输入完整的时间段!'
          });
          return;
        }
      });
    },
    selectTimeSlot(timeSlotId) {
      this.selectedTimeSlotId = timeSlotId;
    },
    deleteTimeSlot(timeSlotId) {
      this.$confirm('确定要删除这个时间段吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // Call API to delete the time slot
          const success =  await this.loaddeleteTime(timeSlotId);
          if (success) {
             this.timeSlots = this.timeSlots.filter(slot => slot.id !== timeSlotId);
            if (this.selectedTimeSlotId === timeSlotId) {
             this.selectedTimeSlotId = null;
           }
          }
        } catch (err) {
          console.error('Delete time slot error:', err);
          this.$message({
            type: 'error',
            message: '删除失败!'
          });
        }
      }).catch(() => {
        // User cancelled deletion
      });
    }
  }
};
</script>

<style scoped>
.time-dialog-slots-container {
  display: flex;
  align-items: center;
}

.time-input {
  margin: 0 5px;
}

.time-separator {
  margin: 0 5px;
  font-weight: bold;
}

.card-container {
  margin-bottom: 20px;
  margin-top: 20px;
}

.seat-card-col {
  margin-bottom: 20px;
}

.seat-card {
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.seat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.seat-card.active {
  border-color: #409EFF;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.5);
}

.seat-actions {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 10;
}

.seat-info > div {
  margin-bottom: 8px;
  font-size: 14px;
}

.seat-info > div:last-child {
  margin-bottom: 0;
}

.time-tags-container {
  margin-top: 15px;
}

.time-tag {
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
  position: relative;
  padding-right: 25px;
}

.time-tag.selected {
  border-color: #409EFF;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
}

.delete-time-icon {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  cursor: pointer;
}

.dialog-footer {
  text-align: right;
}
</style>